﻿using System;
using System.Collections.Generic;
using System.Linq;
using Kaio.Core;

namespace MvcForum.Net.Bussiness
{
    public class ForumRepo
    {

        public static List<Forum> ListAll()
        {

            var _data = (List<Forum>)CacheHelper.Get(CacheKeys.FORUM_ALL);

            if (_data == null)
            {
                _data = MainDB.Instant.Forum_List(0).ExecuteTypedList<Forum>();

                if (_data.Count > 0)
                {
                    CacheHelper.Add(CacheKeys.FORUM_ALL, _data);
                }

            }

            return _data;

        }
        


        public static List<ForumUrl> Jump()
        {

            var _forumUrls= ForumContext.GetNavMenu();
            

            var _f =ListAll().Select(forum => new ForumUrl
                                                     {
                                                         Title = string.Format("{0}{1}", ForumContext.Padding(forum.Level), forum.ForumName),
                                                         //Url = ForumContext.ForumLink(forum.ForumId, forum.ForumName, null),
                                                         Url = ForumContext.GetAbsoluteUrl(ForumUrls.FIND_FORUM, forum.ForumId),
                                                         CssClass = forum.Level==1?"bold":string.Empty
                                                     }).ToList();

            _forumUrls.AddRange(_f);

            return _forumUrls;
        }

        public static List<ForumUrl> BuildForumUrls(List<Forum> forums)
        {

            return forums.Select(forum => new ForumUrl
                                                     {
                                                         Title = forum.ForumName,
                                                         Url = ForumContext.ForumLink(forum.ForumId, forum.ForumName, null)

                                                     }).ToList();

        }


        public static List<ForumUrl> BuildForumUrls(int forumId)
        {
            var _list = new List<Forum>();

            SubToParent(forumId, ref _list);

            return BuildForumUrls(_list);
        }

        public static List<Forum> Sub(int _parentId)
        {
            var _data = ListAll();

            if (_data != null && _data.Count > 0)
            {

                return _data.FindAll(_x => _x.ParentId == _parentId);
                

               // return _a;//.Sort((x, y) => int.MaxValue(x.SortOrder,y.SortOrder));

            }

            return null;

        }


        public static List<Forum> InHomePage(int parent)
        {

            var _data = Sub(parent);
            if (_data != null && _data.Count > 0)
            {
                return _data.FindAll(x => x.VisibleAtHomePage);
            }


            return null;
        }



        public static Forum Info(int _id)
        {
            var _data = ListAll();
            if (_data != null && _data.Count > 0)
            {
                return _data.Find(_x => _x.ForumId == _id);
            }

            return null;
        }


        public static Forum Detail(int id)
        {
            var _data = MainDB.Instant.Forum_Detail(id).ExecuteTypedList<Forum>();

            return _data.Count > 0 ? _data[0] : null;
        }



        public static void SubToParent(int _id, ref List<Forum> _categories)
        {

            Forum _current = Info(_id);

            if (_current != null)
            {

                SubToParent(_current.ParentId, ref  _categories);
                _categories.Add(_current);
            }


        }




        public static void Save(Forum f)
        {

            MainDB.Instant.Forum_Save(f.ForumId,f.Icon,f.ForumName,f.ParentId,f.Keywords,f.Description,f.SortOrder,f.RemoteUrl,f.IsLocked,f.AllowPostWithIn,f.ModerateType,f.AllowRoles,f.VisibleAtHomePage,f.IncreaseMemberPosts,f.OrderBy,f.SortDirection,f.TopicsPerPage,f.PostsPerPage,f.AllowSearch).Execute();


            CacheHelper.Remove(CacheKeys.FORUM_ALL);

        }

        public static void ToggleLock(int id)
        {

            MainDB.Instant.Forum_ToggleLock(id).Execute();

            CacheHelper.Remove(CacheKeys.FORUM_ALL);
        }


        public static void UpdateLastPost(int forumId)
        {

            var _forums = new List<Forum>();
            SubToParent(forumId, ref _forums);

            var t = ForumContext.ThreadPool;

            foreach (Forum f in _forums)
            {

                

                int totalTopics;
                int totalReplies;
                var _lastPost = LastPost(f.ForumId, out totalTopics, out totalReplies);
                if (_lastPost != null)
                {
                    var _sp = MainDB.Instant.Forum_UpdateLastPost(f.ForumId, totalTopics, totalReplies,
                                                                  _lastPost.UserName, _lastPost.TopicId,
                                                                  _lastPost.Created, _lastPost.TopicName);

                 //   _sp.Execute();
                    
                   t.QueueWorkItem(_sp.Execute);

                }


            }

            
           /* t.Start();*/
            //t.WaitForIdle();
            //t.Shutdown();

            // Clear Cache Update Last Post
            //CacheHelper.Remove(CacheKeys.FORUM_ALL);

            ForumContext.ThreadPool.QueueWorkItem(CacheHelper.Clear);
        }


        public static Topic LastPost(int forumId, out int totalTopics, out int totalReplies)
        {
            var _sp = MainDB.Instant.Forum_GetLastPost(forumId);

            var _data = _sp.ExecuteTypedList<Topic>();

            totalTopics = Convert.ToInt32(_sp.OutputParameters.GetParameter("TotalTopics").ParameterValue);

            totalReplies = Convert.ToInt32(_sp.OutputParameters.GetParameter("TotalReplies").ParameterValue);

            return _data.Count > 0 ? _data[0] : null;

        }


       /* public static void ResetAllCounterAndLastPosts()
        {
            var _forums = ListAll();
            foreach (Forum f in _forums)
            {

                int totalTopics;
                int totalReplies;
                var _lastPost = LastPost(f.ForumId, out totalTopics, out totalReplies);
                if (_lastPost != null)
                {

                    var _sp = MainDB.Instant.Forum_UpdateLastPost(f.ForumId, totalTopics, totalReplies,
                                                                 _lastPost.UserName, _lastPost.TopicId,
                                                                 _lastPost.Created, _lastPost.TopicName);

                    //   _sp.Execute();

                    ForumContext.ThreadPool.QueueWorkItem(_sp.Execute);
                }
                   // MainDB.Instant.Forum_UpdateLastPost(f.ForumId, totalTopics, totalReplies, _lastPost.UserName, _lastPost.TopicId, _lastPost.Created, _lastPost.TopicName).Execute();
            }


            var _users = UsersRepo.All();
            foreach (var u in _users)
            {
                var _sp = MainDB.Instant.User_CalculateTotalPosts(u.UserId);

                ForumContext.ThreadPool.QueueWorkItem(_sp.Execute);
            }

            ForumContext.ThreadPool.QueueWorkItem(CacheHelper.Clear);

            // Clear Cache Update Last Post
            //CacheHelper.Remove(CacheKeys.FORUM_ALL);
        }*/


        public static void Del(string ids)
        {
            MainDB.Instant.Forum_Delete(ids).Execute();

            CacheHelper.Remove(CacheKeys.FORUM_ALL);
        }

       

    }
}
